#include "DGL3Common.glsl"
#include "DGL3PickCommon.glsl"
#include "DGL3ProgramEnums.inc"

//-----------------------------------------

#ifdef VERTEX_SHADER

	layout(location = 0) in vec3 aPosition;
	layout(location = GE_VA_Transform) in ivec2 aAssigns;

	out vec2 screenPosition;

	void main(void)
	{
		gl_Position = GetModelMatrix(aAssigns.x) * vec4(aPosition, 1.0);
		vec4 screenPos4 = (uProjectionMatrix * uViewMatrix * GetModelMatrix(aAssigns.x)) * vec4(aPosition, 1.0);
		screenPosition = screenPos4.xy / screenPos4.w;
	}

#endif

//-----------------------------------------

#ifdef GEOMETRY_SHADER

	layout(points) in; 
	layout(points, max_vertices = 1) out;

	uniform vec3 uRayOrigin;
	uniform vec3 uRayDirection;
	uniform vec2 uRayOrigin2d;
	uniform float uTolerance;

	in vec2 screenPosition[];
	// position in normalized device coordinates
	out vec3 ndcPos; 

	void main(void)
	{
		vec3 point = gl_in[0].gl_Position.xyz;
		vec2 point2d = screenPosition[0];

		float distance2d = length( uRayOrigin2d - point2d );
		if ( distance2d <= uTolerance )
		{
			vec3 hitPoint;
			hitPoint = point; //FindHitPointToPoint3d( uRayOrigin, uRayDirection, point );
			gl_Position = uProjectionMatrix * uViewMatrix * vec4( hitPoint, 1.0 );
			ndcPos = gl_Position.xyz / gl_Position.w;
			
			EmitVertex();
			EndPrimitive();
		}
	}

#endif

//-----------------------------------------

#ifdef FRAGMENT_SHADER

	in vec3 ndcPos;
	layout(location = 0) out vec4 fragColor;
	
	void main(void)
	{
		// convert ndcPos from range [-1;1] to range [0;1]
		fragColor = vec4( (ndcPos+1)/2, 0 );
	}

#endif
